﻿
using QFramework;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace ProjectChildhood
{
    public interface IChallengeSystem : QFramework.IToolBarSystem
    {
        /// <summary>
        /// 存储挑战信息
        /// </summary>
        List<Challenge> ChallengeList { get; } 

        //已完成挑战
        List<Challenge> FinishedChallengeList { get; } 

        //活跃中挑战
        List<Challenge> ActiveChallengeList { get; }

        void LoadData();
        void ResetData();
        void SaveData();
    }

    public class ChallengeSystem : AbstractSystem, IChallengeSystem 
    {
        /// <summary>
        /// 每天果子成熟的数量
        /// </summary>
        public static BindableProperty<int> RipeAndHarvestCountInCurrentDay = new BindableProperty<int>(0);
        public static int HarvestedCarrotCount = 0;
        public static int HarvestedPotatoCount = 0;
        public static int HarvestedTomatoCount = 0;
        public static int HarvestedPumpkinCount = 0;
        public static int HarvestedBeanCount = 0;

        /// <summary>
        /// 存储挑战信息
        /// </summary>
        public List<Challenge> ChallengeList { get; } = new List<Challenge>();

        //已完成挑战
        public List<Challenge> FinishedChallengeList { get; } = new List<Challenge>();
        //活跃中挑战
        public List<Challenge> ActiveChallengeList { get; } = new List<Challenge>();


        /// <summary>
        /// 植物被收割的事件
        /// </summary>
        public static EasyEvent<IPlant> OnPlantHarvast = new EasyEvent<IPlant>();

        /// <summary>
        /// 挑战完成时的事件
        /// </summary>
        public static EasyEvent<Challenge> OnChallengeFinish = new EasyEvent<Challenge>();

        void LoadChallenges()
        {
            ChallengeList.Clear();
            ActiveChallengeList.Clear();
            FinishedChallengeList.Clear();

            ChallengeList.Add(new CustomChallenge()
               .Key("分别收获两枚土豆，两枚西红柿，两枚南瓜和两枚豆角")
               .OnCheckFinish(self => { return HarvestedPotatoCount >= 2 && HarvestedTomatoCount >= 2 && HarvestedPumpkinCount >= 2 && HarvestedBeanCount >= 2; }));
            ChallengeList.Add(new CustomChallenge()
                .Key("赚取20枚金币")
                .OnCheckFinish(self => { return Global.Gold.Value >= 20; }));
            ChallengeList.Add(new CustomChallenge()
                .Key("同一天收获两枚水果")
                .OnCheckFinish(self => { return RipeAndHarvestCountInCurrentDay.Value >= 2; }));
            ChallengeList.Add(new CustomChallenge()
                .Key("共收获十枚土豆，并去做成薯条")
                .OnCheckFinish(self => { return HarvestedPotatoCount >= 10; }));
            ChallengeList.Add(new CustomChallenge()
                .Key("收获一颗胡萝卜和一个番茄还有一个果实")
                .OnCheckFinish(self => { return HarvestedCarrotCount >= 1 && HarvestedTomatoCount >= 1; }));
        }

        public void LoadData()
        {
            foreach (var challenge in ChallengeList)
            {
                challenge.State = (Challenge.EChallengeState) PlayerPrefs.GetInt(challenge.Name, (int)Challenge.EChallengeState.Unenable);

                if (challenge.State == Challenge.EChallengeState.Enable)
                {
                    ActiveChallengeList.Add(challenge);
                }
                else if (challenge.State == Challenge.EChallengeState.Finished)
                {
                    FinishedChallengeList.Add(challenge);
                }
            }

            RipeAndHarvestCountInCurrentDay.Value = PlayerPrefs.GetInt(nameof(RipeAndHarvestCountInCurrentDay), RipeAndHarvestCountInCurrentDay.Value);
            HarvestedCarrotCount = PlayerPrefs.GetInt(nameof(HarvestedCarrotCount), HarvestedCarrotCount);
            HarvestedPumpkinCount = PlayerPrefs.GetInt(nameof(HarvestedPumpkinCount), HarvestedPumpkinCount);
            HarvestedPotatoCount = PlayerPrefs.GetInt(nameof(HarvestedPotatoCount), HarvestedPotatoCount);
            HarvestedTomatoCount = PlayerPrefs.GetInt(nameof(HarvestedTomatoCount), HarvestedTomatoCount);
            HarvestedBeanCount = PlayerPrefs.GetInt(nameof(HarvestedBeanCount), HarvestedBeanCount);
        }

        public void ResetData()
        {
            LoadChallenges();

            foreach(var challenge in ChallengeList) 
            {
                challenge.State = Challenge.EChallengeState.Unenable;
            }

            RipeAndHarvestCountInCurrentDay.Value = 0;
            HarvestedCarrotCount = 0;
            HarvestedPumpkinCount = 0;
            HarvestedPotatoCount = 0;
            HarvestedBeanCount = 0;

            SaveData();
        }

        public void SaveData()
        {
            foreach (Challenge challenge in ChallengeList)
            {
                PlayerPrefs.SetInt(challenge.Name, (int)challenge.State);
            }

            PlayerPrefs.SetInt(nameof(RipeAndHarvestCountInCurrentDay), RipeAndHarvestCountInCurrentDay.Value);
            PlayerPrefs.SetInt(nameof(HarvestedCarrotCount), HarvestedCarrotCount);
            PlayerPrefs.SetInt(nameof(HarvestedPumpkinCount), HarvestedPumpkinCount);
            PlayerPrefs.SetInt(nameof(HarvestedPotatoCount), HarvestedPotatoCount);
            PlayerPrefs.SetInt(nameof(HarvestedTomatoCount), HarvestedTomatoCount);
            PlayerPrefs.SetInt(nameof(HarvestedBeanCount), HarvestedBeanCount);
        }

        protected override void OnInit()
        {
            LoadChallenges();

            // 收割果实的事件监听
            OnPlantHarvast.Register(plant =>
            {
                if (plant is Plant)
                {
                    var plantObj = plant as Plant;
                    if (plantObj.Name == "fruit") RipeAndHarvestCountInCurrentDay.Value++;
                    else if (plantObj.Name == "potato") HarvestedPotatoCount++;
                    else if (plantObj.Name == "tomato") HarvestedTomatoCount++;
                    else if (plantObj.Name == "pumpkin") HarvestedPumpkinCount++;
                    else if (plantObj.Name == "bean") HarvestedBeanCount++;
                    else if (plantObj.Name == "carrot") HarvestedCarrotCount++;
                }
            });

            // 帧更新检测 挑战的完成情况
            ActionKit.OnUpdate.Register(() =>
            {
                bool hasFinishedChallenge = false; // 是否存在已完成

                foreach (var challenge in ActiveChallengeList)
                {
                    //Debug.Log("@@@@" + "遍历到事件!");
                    if (challenge.State == Challenge.EChallengeState.Unenable)
                    {
                        challenge.OnStart();
                        challenge.State = Challenge.EChallengeState.Enable;
                    }

                    if (challenge.State == Challenge.EChallengeState.Enable)
                    {
                        if (challenge.CheckFinish())
                        {
                            //挑战完成
                            challenge.OnFinish();
                            challenge.State = Challenge.EChallengeState.Finished;
                            OnChallengeFinish.Trigger(challenge);
                            FinishedChallengeList.Add(challenge);
                            hasFinishedChallenge = true;
                        }
                    }
                }
                if (hasFinishedChallenge)
                {
                    ActiveChallengeList.RemoveAll(challenge => challenge.State == Challenge.EChallengeState.Finished);
                }

                if (ActiveChallengeList.Count == 0 && FinishedChallengeList.Count != ChallengeList.Count)
                {   
                    //挑战完成再生成一个随机挑战
                    RipeAndHarvestCountInCurrentDay.Value = 0;
                    Challenge randomChallenge = ChallengeList.Where(c => c.State == Challenge.EChallengeState.Unenable).ToList().GetRandomItem();
                    ActiveChallengeList.Add(randomChallenge);
                }
            });
        }
    }
}
